package com.ruoyi.web.controller.deepSeek;

import okhttp3.*;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * deepSeek
 * 官方对话补全
 */
@RestController
@RequestMapping("/api")
public class DeepSeekController {

    @Value("${deepseek.api.token}")
    private String apiToken;

    // 设置超时时间为1分钟
    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.MINUTES)  // 连接超时设置为10分钟
            .readTimeout(10, TimeUnit.MINUTES)     // 读取超时设置为10分钟
            .writeTimeout(10, TimeUnit.MINUTES)    // 写入超时设置为10分钟
            .build();

    @PostMapping("/chat")
    public String chatWithAI(String userMessage) {
        // 构建请求体
        String requestBody = createRequestBody(userMessage);

        // 创建请求体
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, requestBody);

        // 创建请求
        Request request = new Request.Builder()
                .url("https://api.deepseek.com/chat/completions")

                // .url("https://api.deepseek.com")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiToken)
                .build();





        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 请求成功，返回响应体
                return response.body().string();
            } else {
                // 请求失败，返回错误信息
                return "Request failed with status: " + response.code();
            }
        } catch (IOException e) {
            // 捕获异常，返回错误信息
            return "Error during API request: " + e.getMessage();
        }
    }





    // 创建请求体的方法
    private String createRequestBody(String userMessage) {
        return "{\n" +
                "  \"messages\": [\n" +
                "    {\"role\": \"user\", \"content\": \"" + escapeJson(userMessage) + "\"}\n" +
                "  ],\n" +
                "  \"model\": \"deepseek-chat\",\n" +
                "  \"frequency_penalty\": 0,\n" +
                "  \"max_tokens\": 2048,\n" +
                "  \"presence_penalty\": 0,\n" +
                "  \"response_format\": { \"type\": \"text\" },\n" +
                "  \"stop\": null,\n" +
                "  \"stream\": false,\n" +
                "  \"temperature\": 1,\n" +
                "  \"top_p\": 1\n" +
                "}";
    }

    // 防止用户消息中的特殊字符导致JSON格式错误
    private String escapeJson(String str) {
        return str.replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r");
    }
}
